#include "UsrAI.h"
#include<set>
#include <iostream>
#include<unordered_map>
#include <vector>
#include <cmath>

using namespace std;

typedef pair<int, int> PII;

tagGame tagUsrGame;
ins UsrIns;

const int i32_inf = 0x3f3f3f3f;

//  ##########################--参数对照表--########################

//  --------------------------------------------------------------


//  -----------struct tagInfo--------------
//  ####所有状态变量的参数名####

//{
//    vector<tagBuilding> buildings;        我方建筑列表
//    vector<tagFarmer> farmers;            我方农民列表，包括运输船和渔船
//    vector<tagArmy> armies; //            我方军队列表，包括战船
//    vector<tagBuilding> enemy_buildings;  敌方建筑列表
//    vector<tagFarmer> enemy_farmers;      敌方农民列表
//    vector<tagArmy> enemy_armies;         敌方军队列表
//    vector<tagResource> resources;        资源列表
//    以上列表中的元素顺序每一帧都是随机的
//    map<int, int> ins_ret;                指令返回值，map<id, ret>
//    TerrainData* theMap;                  一个指向二维数组的指针,内部元素为tagTerrain类型，定义见后文，表示地图信息，[BlockDR][BlockUR]。
//    int GameFrame;                        当前帧数
//    int civilizationStage;                文明阶段
//    #define CIVILIZATION_STONEAGE 1
//    #define CIVILIZATION_TOOLAGE 2
//    int Wood;                             木材数量
//    int Meat;                             肉类数量
//    int Stone;                            石头数量
//    int Gold;                             黄金数量
//    int Human_MaxNum;                     最大人口数量
//};

//  -----------struct tagBuilding------------

//{
//    int BlockDR,BlockUR; //区块坐标
//    int Type; // 建筑类型
//    int SN; // 序列号
//    int Blood; // 当前血量
//    int MaxBlood; // 最大血量
//    int Percent; // 完成百分比
//    int Project; // 当前项目
//    int ProjectPercent; // 项目完成百分比
//    int Cnt; // 剩余资源量（仅农田）
//};

//--------------struct tagResource----------------

//{
//    double DR,UR; //细节坐标
//    int BlockDR,BlockUR; //区块坐标
//    int Type; // 资源类型
//    int SN; // 序列号
//    int ProductSort; // 产品种类
//    int Cnt; // 剩余资源数量
//    int Blood; // 当前血量
//};

//---------------struct tagHuman-----------------

//{
//    double DR,UR; //细节坐标
//    int BlockDR,BlockUR; //区块坐标
//    double DR0,UR0; // 目的地坐标
//    int NowState; // 当前状态
//    int WorkObjectSN; // 工作对象序列号
//    int Blood; // 当前血量
//    int SN; // 序列号
//    int attack; // 攻击力
//    int rangedDefense; // 远程防御
//    int meleeDefense; // 近战防御
//};

//----------------struct tagFarmer: public tagHuman-----------


//{
//    int ResourceSort; // 手持资源种类
//    int Resource; // 手持资源数量；如果是运输船，则代表单位数量
//    int FarmerSort; // 村民的类型： 0表示陆地生产单位，1表示运输船，2表示渔船
//};


//----------------struct tagArmy:public tagHuman----------------
//{
//int Sort;   //军队种类，详细定义见后文
//};





//---------------------------------------------------------------




//--------------------------自定义宏对照表-------------------------

#define COLLECT_IDLE_FRAMER 0


//---------------------------------------------------------------

// 定义全局变量，方便后序使用

// 存储每一帧的所有变量的状态
tagInfo info;

char cur_map[128][128];
bool grass_map[128][128];
int resource_map[128][128];

unordered_map <int, int> resource_mp, building_mp; // 存序列号对应的类型
unordered_map <string, tagFarmer> mp_job_farmer; // 工作与农民的映射
unordered_map <int, pair<int, int>> human_pos; // 人物对应的位置，判定是否不动了


// 可能用得到的全局变量

vector <tagFarmer> farmer_idle;
vector <tagFarmer> farmer_cut_tree;
vector <tagFarmer> farmer_pick_stone;
vector <tagFarmer> farmer_go_fishing;
vector <tagFarmer> farmer_hunting;
vector <tagFarmer> farmer_building_home;
vector <tagFarmer> farmer_building_granary;
vector <tagFarmer> farmer_building_stock;
vector <tagFarmer> farmer_building_armycamp;
vector <tagFarmer> farmer_building_arrowtower;
vector <tagFarmer> farmer_building_farm;
vector <tagFarmer> farmer_building_market;
vector <tagFarmer> farmer_building_range;
vector <tagFarmer> farmer_building_stable;
vector <tagFarmer> farmer_building_dock;

vector <tagFarmer> farmer_sailing;
vector <tagFarmer> farmer_wood_boat;

vector <tagArmy> army_ship;
vector <tagArmy> army_clubman;
vector <tagArmy> army_bowman;
vector <tagArmy> army_slinger;
vector <tagArmy> army_scout;
vector <tagArmy> army_swordsman;


int cnt_home = 0;   // 房子
int cnt_granary = 0;    // 谷仓
int cnt_stock = 0;  // 仓库
int cnt_armycamp = 0;   // 兵营
int cnt_arrowtower = 0; // 箭塔
int cnt_farm = 0;   // 农场
int cnt_market = 0; // 市场
int cnt_range = 0;  // 靶场
int cnt_stable = 0; // 马厩
int cnt_dock = 0;   // 船坞

int cnt_farmers = 0;    // 农民
int cnt_sailings = 0;   // 渔船
int cnt_wood_boats = 0; // 运输船


int cnt_ships = 0;  // 战船
int cnt_clubman = 0; // 棍棒兵
int cnt_slinger = 0; // 斧头兵
int cnt_swordsman = 0; // 战斧兵
int cnt_bowman = 0; // 弓兵
int cnt_scout = 0; // 侦查骑兵

int cnt_enemy_ship = 0;
int cnt_enemy_clubman = 0;
int cnt_enemy_slinger = 0;
int cnt_enemy_swordsman = 0;
int cnt_enemy_bowman = 0;
int cnt_enemy_scout = 0;

int cnt_near_tree_stock = 0;
int cnt_near_food_stock = 0;
int cnt_near_stone_stock = 0;

vector <PII> our_near_water_block, enemy_near_water_block;
vector <PII> our_near_block_water, enemy_near_block_water;

unordered_map<int, PII> dock_building_tasks; // SN->位置

//------------------------功能型函数-------------------------

// 计算两点之间的距离
double UsrAI::cal_dis(double x1, double y1, double x2, double y2) {
    return sqrt(pow(x2 - x1, 2) + pow(y2 - y1, 2));
}

//------------------------地图有关的函数----------------------


// 用于判断该坐标是否空闲/被占用
bool space_map[128][128];

// 用于存储己方大陆
bool our_grassmap[128][128];
// 用于存储敌方大陆
bool enemy_grassmap[128][128];

// 动态获取地图   获取的地图存地形以及高度
void UsrAI::BuildMap() {
    memset(grass_map, false, sizeof(grass_map));
    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j < 128; j ++) {
            // 如果为陆地，则设置高度
            if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                grass_map[i][j] = true;
                if ((*info.theMap)[i][j].height == -1) cur_map[i][j] = '-';
                else cur_map[i][j] = '0' + (*info.theMap)[i][j].height;
            }

            // 如果为海洋，则设置为'#'
            else if ((*info.theMap)[i][j].type == MAPPATTERN_OCEAN)
                cur_map[i][j] = '#';
            // 如果为未知探索区域，则设置为'?'
            else cur_map[i][j] = '?';
        }
    }
}

void UsrAI::ResourceMap() {
    for (auto &e : info.resources) {
        resource_map[e.BlockDR][e.BlockUR] = e.Type;
    }
}

// 寻找大小合适，高度一致的区域
bool UsrAI::find_empty_area(int x, int y) {
    if (cur_map[x][y] == '#' || cur_map[x][y] == '?' || cur_map[x][y] == '-') return false;

    int h = cur_map[x][y] - '0';
    for (int i = x; i < x + 3; i ++) {
        for (int j = y; j < y + 3; j ++) {
            if (cur_map[i][j] - '0' != h || space_map[i][j]) return false;
        }
    }

    return true;

}

pair<int, int> UsrAI::find_water(int x, int y) {
    for (int i = x; i < x + 2; i ++) {
        for (int j = y; j < y + 2; j ++) {
            if (cur_map[i][j] != '#' || space_map[i][j]) return {-1, -1};
        }
    }

    for (auto &e : info.resources)
    {
        if (e.Type == RESOURCE_FISH)
        {
            if (abs(e.BlockDR - x) <= 2 || abs(e.BlockUR - y) <= 2) return {-1, -1};
        }
    }

    if (grass_map[x - 1][y] && grass_map[x - 1][y + 1] && ! space_map[x - 1][y] && !space_map[x - 1][y + 1]) {
        return {x, y};
    } else if  (grass_map[x + 2][y] && grass_map[x + 2][y + 1] && !space_map[x + 2][y] && !space_map[x + 2][y + 1]) {
        return {x, y};
    } else if (grass_map[x][y - 1] && grass_map[x + 1][y - 1] && !space_map[x][y - 1] && !space_map[x + 1][y - 1]) {
        return {x, y};
    } else if (grass_map[x][y + 2] && grass_map[x + 1][y + 2] && !space_map[x][y + 2] && !grass_map[x + 1][y + 2]) {
        return {x, y};
    }

    return {-1, -1};
}

//寻找合适的坐标建造建筑
pair<int, int> UsrAI::bfs(int x, int y) {
    int dx[] = {1, 0, -1, 0};
    int dy[] = {0, 1, 0, -1};

    bool st[128][128] = {false};

    queue<pair<int, int>> q;
    q.push({x, y});
    st[x][y] = true;

    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        cout << t.first <<"   " <<t.second << endl;

        for (int i = 0; i < 4; i ++) {
            int new_x = t.first + dx[i], new_y = t.second + dy[i];

            if (new_x < 0 || new_x > 127 || new_y < 0 || new_y > 127) continue;
            if (st[new_x][new_y] || space_map[new_x][new_y]) continue;

            if (find_empty_area(new_x, new_y)) return {new_x, new_y};

            st[new_x][new_y] = true;
            q.push({new_x, new_y});
        }
    }

    return {0, 0};
}



// 测试打印地图，感觉目前并没有什么用
void UsrAI::TestMap() {
    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j < 128; j ++)
            printf("%c ", cur_map[i][j]);
        puts("");
    }

    printf("The map is done.\n");
}

// 更新占用地图

void UsrAI::Init_SpaceMap() {
    memset(space_map, false, sizeof(space_map));

    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j < 128; j ++) {
            if (cur_map[i][j] == '?' || cur_map[i][j] == '-')
                space_map[i][j] = false;

        }
    }

    // 遍历建筑，更新占用空间
    auto e = info.buildings;

    for(int i = 0; i < e.size(); i ++) {
        int e_type = e[i].Type; // 记录建筑类型
        int x = e[i].BlockDR, y = e[i].BlockUR; // 记录块坐标

        if (e_type == BUILDING_HOME)
            for (int k = x; k < x + 2; k ++)
                for (int q = y; q < y + 2; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_GRANARY)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_CENTER)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_STOCK)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_FARM)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_MARKET)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_ARROWTOWER)
            for (int k = x; k < x + 2; k ++)
                for (int q = y; q < y + 2; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_ARMYCAMP)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_STABLE)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_RANGE)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_DOCK)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
    }

    e = info.enemy_buildings;

    for(int i = 0; i < e.size(); i ++) {
        int e_type = e[i].Type; // 记录建筑类型
        int x = e[i].BlockDR, y = e[i].BlockUR; // 记录块坐标

        if (e_type == BUILDING_HOME)
            for (int k = x; k < x + 2; k ++)
                for (int q = y; q < y + 2; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_GRANARY)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_CENTER)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_STOCK)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_FARM)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_MARKET)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_ARROWTOWER)
            for (int k = x; k < x + 2; k ++)
                for (int q = y; q < y + 2; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_ARMYCAMP)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_STABLE)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_RANGE)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
        else if (e_type == BUILDING_DOCK)
            for (int k = x; k < x + 3; k ++)
                for (int q = y; q < y + 3; q ++)
                    space_map[k][q] = true;
    }

    for (auto &e : info.resources) {
        int x = e.BlockDR, y = e.BlockUR;
        space_map[x][y] = true; // 表示被占用
    }

    for (auto &e : info.farmers) {
        int x = e.BlockDR, y = e.BlockUR;
        space_map[x][y] = true;
    }
}

//----------------------------------------------------------------


//----------------------------建筑类-------------------------------

// 寻找市镇中心  返回PII, 为左下角坐标
pair<int, int> UsrAI::find_Center() {
    // x, y是市镇中心中心坐标
    int x = 0, y = 0;
    auto &e = info.buildings;

    for (int i = 0; i < e.size(); i ++) {
        if (e[i].Type == BUILDING_CENTER) {
            x = e[i].BlockDR;
            y = e[i].BlockUR;
            break;
        }
    }


    return {x, y};
}

// 寻找房屋
pair<int, int> UsrAI::find_Home() {
    for (auto &e : info.buildings) {
        if (e.Type == BUILDING_HOME) {
            return {e.BlockDR, e.BlockUR};
        }
    }

    return {-1, -1};
}

// 支配建筑生产工作

void UsrAI::Building_produce(int op) {
    if (op == BUILDING_CENTER_CREATEFARMER) { // 生产一个村民
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_CENTER && e.Project == 0 && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_CENTER_CREATEFARMER);
                break;

            }
        }
    } else if (op == BUILDING_ARMYCAMP_CREATE_CLUBMAN) { // 生产一个斧头兵
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_ARMYCAMP && e.Project == 0 && info.Meat >= BUILDING_ARMYCAMP_CREATE_CLUBMAN_FOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_ARMYCAMP_CREATE_CLUBMAN);
                break;

            }
        }
    } else if (op == BUILDING_ARMYCAMP_CREATE_SLINGER) { // 生产一个投石兵
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_ARMYCAMP && e.Project == 0 && info.Meat >= BUILDING_ARMYCAMP_CREATE_SLINGER_FOOD && info.Stone >= BUILDING_ARMYCAMP_CREATE_SLINGER_STONE && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_ARMYCAMP_CREATE_SLINGER);
                break;

            }
        }
    } else if (op == BUILDING_RANGE_CREATE_BOWMAN) { // 生产一个弓箭兵
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_RANGE && e.Project == 0 && info.Meat >= BUILDING_RANGE_CREATE_BOWMAN_FOOD && info.Wood >= BUILDING_RANGE_CREATE_BOWMAN_WOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_RANGE_CREATE_BOWMAN);
                break;

            }
        }
    } else if (op == BUILDING_STABLE_CREATE_SCOUT) { // 生产一个侦查骑兵
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_STABLE && e.Project == 0 && info.Meat >= BUILDING_STABLE_CREATE_SCOUT_FOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_STABLE_CREATE_SCOUT);
                break;

            }
        }
    } else if (op == BUILDING_DOCK_CREATE_SAILING) { // 生产一艘渔船
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_DOCK && e.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_DOCK_CREATE_SAILING);
                break;

            }
        }
    } else if (op == BUILDING_DOCK_CREATE_WOOD_BOAT) { // 生产一艘运输船
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_DOCK && e.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_WOOD_BOAT_WOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_DOCK_CREATE_WOOD_BOAT);
                break;

            }
        }
    } else if (op == BUILDING_DOCK_CREATE_SHIP) { // 生产一艘战船
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_DOCK && e.Project == 0 && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD && info.farmers.size() < info.Human_MaxNum) {
                UsrAI::BuildingAction(e.SN, BUILDING_DOCK_CREATE_SHIP);
                break;

            }
        }
    }
}

// 统计建筑数量

int UsrAI::cal_buildings(int op) {
    int cnt = 0;

    if (op == BUILDING_HOME) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_HOME) cnt ++;
        }
    } else if (op == BUILDING_GRANARY) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_GRANARY) cnt ++;
        }
    } else if (op == BUILDING_STOCK) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_STOCK) cnt ++;
        }
    } else if (op == BUILDING_ARMYCAMP) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_ARMYCAMP) cnt ++;
        }
    } else if (op == BUILDING_ARROWTOWER) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_ARROWTOWER) cnt ++;
        }
    } else if (op == BUILDING_FARM) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_FARM) cnt ++;
        }
    } else if (op == BUILDING_MARKET) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_MARKET) cnt ++;
        }
    } else if (op == BUILDING_RANGE) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_RANGE) cnt ++;
        }
    } else if (op == BUILDING_STABLE) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_STABLE) cnt ++;
        }
    } else if (op == BUILDING_DOCK) {
        for (auto &e : info.buildings) {
            if (e.Type == BUILDING_DOCK) cnt ++;
        }
    }

    return cnt;
}

//---------------------------------------------------------------


//----------------------------人物类------------------------------


// 指派村民去最近的制定的资源点干活
// job:指派空闲的村民去干活

void UsrAI::farmers_to_work(tagFarmer &e, int job) { //*****************还没写完*************
    if (job == RESOURCE_TREE) { // 如果砍树，则派村民去最近的树砍
        int targetTree = 0; // 存储最近树木的SN（身份证）
        double shortest_dist = 1e9;
        for (auto &y : info.resources) { // 寻找最近的树木,得到最近的树木的身份证
            if (y.Type != RESOURCE_TREE) continue;
            double dist = cal_dis(e.DR, e.UR , y.DR, y.UR);
            if (shortest_dist > dist) {
                shortest_dist = dist;
                targetTree = y.SN;
            }
        }
        if(targetTree) HumanAction(e.SN, targetTree);
    } else if (job == RESOURCE_STONE) {
        int targetStone = 0; // 存储最近树木的SN（身份证）
        double shortest_dist = 1e9;
        for (auto &y : info.resources) { // 寻找最近的树木,得到最近的树木的身份证
            if (y.Type != RESOURCE_STONE) continue;
            double dist = cal_dis(e.DR, e.UR , y.DR, y.UR);
            if (shortest_dist > dist) {
                shortest_dist = dist;
                targetStone = y.SN;
            }
        }

        if (targetStone) UsrAI::HumanAction(e.SN, targetStone);
    } else if (job == RESOURCE_GAZELLE) {
        int targetgazelle = 0;
        for (auto &y : info.resources) {
            if (y.Type == RESOURCE_GAZELLE) { // 瞪羚
                targetgazelle = y.SN;
                break;
            }
        }

        if (targetgazelle) UsrAI::HumanAction(e.SN, targetgazelle);
    } else if (job == RESOURCE_FISH) {
        int targetfish = 0;

        int now_x = e.BlockDR, now_y = e.BlockUR;
        double dis = 1e8;
        for (auto &y : info.resources) {
            if (y.Type == RESOURCE_FISH) {
                double now_dis = cal_dis((double)now_x, (double)now_y, (double)y.BlockDR, (double)y.BlockUR);
                if (dis > now_dis) {
                    dis = now_dis;
                    targetfish = y.SN;
                }
            }

//                cout << "find dish poi is" << y.BlockDR << ' ' << y.BlockUR << '\n';
        }

        cout << "fish SN: " << targetfish << '\n';

        if (targetfish) UsrAI::HumanAction(e.SN, targetfish);
    }

}

// 指派村民建筑

// job对照表：
// "home"       房屋
// "granary"    谷仓
// "stock"      仓库
// "armycamp"   兵营
// "arrowtower" 箭塔
// "farm"       农场
// "market"     市场
// "range"      靶场
// "stable"     马厩
// "dock"       船坞

// 没有写判断条件
void UsrAI::farmers_building(int job, tagFarmer &e, int x, int y) {

    if (job == BUILDING_HOME) UsrAI::HumanBuild(e.SN, BUILDING_HOME, x, y);
    else if (job == BUILDING_GRANARY) UsrAI::HumanBuild(e.SN, BUILDING_GRANARY, x, y);
    else if (job == BUILDING_STOCK) UsrAI::HumanBuild(e.SN, BUILDING_STOCK, x, y);
    else if (job == BUILDING_ARMYCAMP)  UsrAI::HumanBuild(e.SN, BUILDING_ARMYCAMP, x, y);
    else if (job == BUILDING_ARROWTOWER) UsrAI::HumanBuild(e.SN, BUILDING_ARROWTOWER, x, y);
    else if (job == BUILDING_FARM) UsrAI::HumanBuild(e.SN, BUILDING_FARM, x, y);
    else if (job == BUILDING_MARKET) UsrAI::HumanBuild(e.SN, BUILDING_MARKET, x, y);
    else if (job == BUILDING_RANGE) UsrAI::HumanBuild(e.SN, BUILDING_RANGE, x, y);
    else if (job == BUILDING_STABLE) UsrAI::HumanBuild(e.SN, BUILDING_STABLE, x, y);
    else if (job == BUILDING_DOCK) UsrAI::HumanBuild(e.SN, BUILDING_DOCK, x, y);
}


// 统计村民数量
int UsrAI::cal_farmers() {
    int cnt = 0;
    for (auto &e : info.farmers) {
        if (e.FarmerSort == 0)
            cnt ++;
    }

    return cnt;
}

// 统计船只数量
int UsrAI::cal_ships(int op) {
    int cnt = 0;
    if (op == BUILDING_DOCK_CREATE_SAILING) {
        for (auto &e : info.farmers) {
            if (e.FarmerSort == 2) // 2表示渔船
                cnt ++;
        }
    } else if (op == BUILDING_DOCK_CREATE_WOOD_BOAT) {
        for (auto &e : info.farmers) {
            if (e.FarmerSort == 1) // 1表示运输船
                cnt ++;
        }
    }

    return cnt;
}

// 统计军队数量
int UsrAI::cal_army(int op) {
    int cnt = 0;
    if (op == AT_CLUBMAN) { // 棍棒兵
        for (auto &e : info.armies) {
            if (e.Sort == AT_CLUBMAN) {
                cnt ++;
            }
        }
    } else if (op == AT_SLINGER) { // 斧头兵
        for (auto &e : info.armies) {
            if (e.Sort == AT_SLINGER) {
                cnt ++;
            }
        }
    } else if (op == AT_SWORDSMAN) { // 战斧兵
        for (auto &e : info.armies) {
            if (e.Sort == AT_SWORDSMAN) {
                cnt ++;
            }
        }
    } else if (op == AT_BOWMAN) { // 弓兵
        for (auto &e : info.armies) {
            if (e.Sort == AT_BOWMAN) {
                cnt ++;
            }
        }
    } else if (op == AT_SCOUT) { // 侦查骑兵
        for (auto &e : info.armies) {
            if (e.Sort == AT_SCOUT) {
                cnt ++;
            }
        }
    } else if (op == AT_SHIP) { // 战船
        for (auto &e : info.armies) {
            if (e.Sort == AT_SHIP) {
                cnt ++;
            }
        }
    }

    return cnt;
}

// 统计敌方单位数量
// 统计敌方单位数量
int UsrAI::cal_enemy(int op) {
    int cnt = 0;
    // 统计敌方战船数量
    if (op == AT_SHIP) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_SHIP) {
                cnt ++;
            }
        }
    }
    // 统计敌方棍棒兵数量
    else if (op == AT_CLUBMAN) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_CLUBMAN) {
                cnt ++;
            }
        }
    }
    // 统计敌方投石兵数量
    else if (op == AT_SLINGER) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_SLINGER) {
                cnt ++;
            }
        }
    }
    // 统计敌方战斧兵数量
    else if (op == AT_SWORDSMAN) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_SWORDSMAN) {
                cnt ++;
            }
        }
    }
    // 统计敌方弓兵数量
    else if (op == AT_BOWMAN) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_BOWMAN) {
                cnt ++;
            }
        }
    }
    // 统计敌方侦察骑兵数量
    else if (op == AT_SCOUT) {
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_SCOUT) {
                cnt ++;
            }
        }
    }
    return cnt;
}

// 将所有村民/军队分类
void UsrAI::find_farmers() {
    farmer_idle.clear();
    farmer_cut_tree.clear();
    farmer_pick_stone.clear();
    farmer_go_fishing.clear();
    farmer_hunting.clear();
    farmer_building_home.clear();
    farmer_building_granary.clear();
    farmer_building_stock.clear();
    farmer_building_armycamp.clear();
    farmer_building_arrowtower.clear();
    farmer_building_farm.clear();
    farmer_building_market.clear();
    farmer_building_range.clear();
    farmer_building_stable.clear();
    farmer_building_dock.clear();

    farmer_wood_boat.clear();
    farmer_sailing.clear();

    army_bowman.clear();
    army_clubman.clear();
    army_scout.clear();
    army_ship.clear();
    army_slinger.clear();
    army_swordsman.clear();

    for (auto &e : info.armies) {
        if (e.Sort == AT_CLUBMAN)
            army_clubman.push_back(e);
        else if (e.Sort == AT_SHIP)
            army_ship.push_back(e);
        else if (e.Sort == AT_BOWMAN)
            army_bowman.push_back(e);
        else if (e.Sort == AT_SCOUT)
            army_scout.push_back(e);
        else if (e.Sort == AT_SLINGER)
            army_slinger.push_back(e);
        else if (e.Sort == AT_SWORDSMAN)
            army_swordsman.push_back(e);
    }

    for (auto &e : info.farmers) {
        if (e.NowState == HUMAN_STATE_IDLE && e.FarmerSort == 0)
            farmer_idle.push_back(e);
    }

    for (auto &e : info.farmers) {
        if (e.NowState == HUMAN_STATE_WORKING && e.FarmerSort == 0) {
            if (resource_mp[e.WorkObjectSN] == RESOURCE_TREE)
                farmer_cut_tree.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == RESOURCE_STONE)
                farmer_pick_stone.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == RESOURCE_FISH)
                farmer_go_fishing.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == RESOURCE_GAZELLE)
                farmer_hunting.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_HOME)
                farmer_building_home.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_GRANARY)
                farmer_building_granary.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_STOCK)
                farmer_building_stock.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_ARMYCAMP)
                farmer_building_armycamp.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_ARROWTOWER)
                farmer_building_arrowtower.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_FARM)
                farmer_building_farm.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_MARKET)
                farmer_building_market.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_RANGE)
                farmer_building_range.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_STABLE)
                farmer_building_stable.push_back(e);
            else if (resource_mp[e.WorkObjectSN] == BUILDING_DOCK)
                farmer_building_dock.push_back(e);
        } else if (e.FarmerSort == 1)
            farmer_wood_boat.push_back(e);
        else if (e.FarmerSort == 2)
            farmer_sailing.push_back(e);
    }

    for (auto it = dock_building_tasks.begin(); it != dock_building_tasks.end();) {
        bool found = false;
        for (auto &building : info.buildings) {
            if (building.BlockDR == it->second.first &&
                building.BlockUR == it->second.second &&
                building.Type == BUILDING_DOCK) {
                // 建造完成，从任务列表中移除
                it = dock_building_tasks.erase(it);
                found = true;
                break;
            }
        }
        if (!found) it++;
    }
}
//--------------------------------------------------------------------------


// 派渔船打鱼
void UsrAI::find_fish() {
    for (auto &e : info.farmers) {
        // 渔船去打鱼
        if (e.FarmerSort == 2 && e.NowState == HUMAN_STATE_IDLE) {
            cout << "find sailings. SN is " << e.SN << '\n';
            farmers_to_work(e, RESOURCE_FISH);
        }
    }
}

// 攻击函数
void UsrAI::attack(int op) {
    if (op == AT_SHIP) {
        tagArmy y;
        bool find = false;
        for (auto &e : info.enemy_armies) {
            if (e.Sort == AT_SHIP) {

                y = e;
                break;
            }
        }

        for (auto &e : army_ship) {
            if (e.NowState == HUMAN_STATE_IDLE || e.NowState == HUMAN_STATE_WALKING) {
                if (abs(e.BlockDR - y.BlockDR) <= 10 && abs(e.BlockUR - y.BlockUR) <= 10) {
                    cout << "find enemy ship. SN : " << y.SN << '\n';
                    cout << "ship  " << e.SN << "  attack  " << y.SN << '\n';
                    HumanAction(e.SN, y.SN);
                }
            }
        }
    }
}

//--------------------------------资源类-------------------------------------

// 让资源的序列号与资源种类一一对应

void UsrAI::init_resources_buildings() {
    for (auto y : info.resources) {
        resource_mp[y.SN] = y.Type;
    }

    for (auto y : info.buildings) {
        building_mp[y.SN] = y.Type;
    }
}

// 统计建筑数量
void UsrAI::init_building_numbers() {
    cnt_home = 0;
    cnt_granary = 0;
    cnt_stock = 0;
    cnt_armycamp = 0;
    cnt_arrowtower = 0;
    cnt_farm = 0;
    cnt_market = 0;
    cnt_range = 0;
    cnt_stable = 0;
    cnt_dock = 0;

    for (auto &e : info.buildings) {
        if (e.Type == BUILDING_HOME) cnt_home ++;
        else if (e.Type == BUILDING_GRANARY) cnt_granary ++;
        else if (e.Type == BUILDING_STOCK) cnt_stock ++;
        else if (e.Type == BUILDING_ARMYCAMP) cnt_armycamp ++;
        else if (e.Type == BUILDING_ARROWTOWER) cnt_arrowtower ++;
        else if (e.Type == BUILDING_FARM) cnt_farm ++;
        else if (e.Type == BUILDING_MARKET) cnt_market ++;
        else if (e.Type == BUILDING_RANGE) cnt_range ++;
        else if (e.Type == BUILDING_STABLE) cnt_stable ++;
        else if (e.Type == BUILDING_DOCK) cnt_dock ++;
    }
}


//------------------------------探索海域模块----------------------------------

unordered_map<int, int> ship_task; // 战船任务状态: 0-探索中 1-战斗中
vector<PII> explore_targets; // 集体探索目标队列

PII enemy_base_center; // 敌方大陆中心位置
unordered_map<int, int> enemy_farmer_task; // 敌方大陆村民任务状态
set<int> enemy_farmers_assigned; // 已分配任务的敌方大陆村民
int enemy_buildings_planned = 0; // 已规划的敌方建筑数量
const int ENEMY_BASE_RADIUS = 15; // 敌方基地建设半径

// 寻找岸边
pair<int, int> UsrAI::find_near_water(int x, int y) {
    for (int dx = -7; dx <= 7; dx ++) {
        for (int dy = -7; dy <= 7; dy ++) {
            int xx = x + dx, yy = y + dy;
            if (xx < 0 || xx >= 128 || yy < 0 || yy >= 128) continue;

            if (enemy_grassmap[xx][yy]) {
                if (cur_map[xx + 1][yy] == '#' ||
                        cur_map[xx][yy + 1] == '#' ||
                        cur_map[xx - 1][yy] == '#' ||
                        cur_map[xx][yy - 1] == '#') {
                    return {xx, yy};
                }
            }
        }
    }

    return {x, y};
}

bool explored_ocean[128][129] = {false}; // 标记未探索海域为false

pair<int, int> landing_poi = {-1, -1}; // 登陆点
queue<pair<int, int>> ship_explore_ob; // 队列存储探索点
bool enemy_land_discovered = false; // 标记是否发现敌方大陆

void UsrAI::init_explore_ocean() {
    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j < 128; j ++) {
            if (cur_map[i][j] != '?')
                explored_ocean[i][j] = true;
        }
    }
}

pair<int, int> UsrAI::get_next_explore_poi(int start_x, int start_y) {
    queue<PII> q;
    bool vis[128][128] = {false};

    q.push({start_x, start_y});
    vis[128][128] = true;

    int dx[] = {0, 1, 0, -1};
    int dy[] = {1, 0, -1, 0};

    while (!q.empty()) {
        auto t = q.front();
        q.pop();

        int x = t.first, y = t.second;

        for (int i = 0; i < 4; i ++) {
            int new_x = x + dx[i];
            int new_y = y + dy[i];

            if (new_x < 0 || new_x >= 128 || new_y < 0 || new_y >= 128) continue;
            if (vis[new_x][new_y]) continue;

            if (cur_map[new_x][new_y] == '#' && !explored_ocean[new_x][new_y]) {
                return {new_x, new_y};
            }

            if (cur_map[new_x][new_y] == '#' && explored_ocean[new_x][new_y]) {
                q.push({new_x, new_y});
                vis[new_x][new_y] = true;
            }
        }
    }

    return {start_x, start_y};
}

void UsrAI::order_ship_explore() {
    static bool is_init = false;
    if (!is_init && !army_ship.empty()) {
        init_explore_ocean();
        is_init = true;
    }

    for (auto &ship : army_ship) {
        if (ship.NowState != HUMAN_STATE_IDLE) continue;

        int curr_x = ship.BlockDR;
        int curr_y = ship.BlockUR;

        auto target = get_next_explore_poi(curr_x, curr_y);
        int tx = target.first;
        int ty = target.second;

        double detail_dr = tx * BLOCKSIDELENGTH;
        double detail_ur = ty * BLOCKSIDELENGTH;

        HumanMove(ship.SN, detail_dr, detail_ur);
        DebugText("战船 " + to_string(ship.SN) + " 探索目标: (" + to_string(tx) + "," + to_string(ty) + ")");

        explored_ocean[tx][ty] = true;
    }
}

// 战船状态枚举
enum ShipState {
    SHIP_EXPLORING,  // 探索中
    SHIP_ATTACKING,  // 战斗中
    SHIP_RETURNING   // 返回基地
};

// 战船状态映射
unordered_map<int, ShipState> ship_states;

// 优化后的探索与战斗函数
void UsrAI::shipExploreAndCombat() {
    // 初始化探索队列
    static bool exploration_init = false;
    if (!exploration_init && !army_ship.empty()) {
        // 从基地向外辐射探索点
        auto center = find_Center();
        for (int r = 10; r <= 110; r += 20) {
            for (int angle = 0; angle < 360; angle += 45) {
                int x = center.first + r * cos(angle * M_PI / 180);
                int y = center.second + r * sin(angle * M_PI / 180);
                if (x >= 0 && x < 128 && y >= 0 && y < 128) {
                    ship_explore_ob.push({x, y});
                }
            }
        }
        exploration_init = true;
    }

    // 处理每艘战船
    for (auto &ship : army_ship) {
        // 初始化状态
        if (ship_states.find(ship.SN) == ship_states.end()) {
            ship_states[ship.SN] = SHIP_EXPLORING;
        }

        // 战斗优先：检查附近是否有敌人
        bool enemy_nearby = false;
        for (auto &enemy : info.enemy_armies) {
            if (enemy.Sort == AT_SHIP) {
                double dist = cal_dis(ship.DR, ship.UR, enemy.DR, enemy.UR);
                if (dist < 8 * BLOCKSIDELENGTH) { // 战斗半径
                    HumanAction(ship.SN, enemy.SN);
                    ship_states[ship.SN] = SHIP_ATTACKING;
                    enemy_nearby = true;
                    DebugText("战船" + to_string(ship.SN) + "攻击敌船" + to_string(enemy.SN));
                    break;
                }
            }
        }

        if (enemy_nearby) continue;

        // 根据状态处理
        switch (ship_states[ship.SN]) {
            case SHIP_EXPLORING:
                if (ship.NowState == HUMAN_STATE_IDLE && !ship_explore_ob.empty()) {
                    auto target = ship_explore_ob.front();
                    ship_explore_ob.pop();
                    double detail_dr = target.first * BLOCKSIDELENGTH;
                    double detail_ur = target.second * BLOCKSIDELENGTH;
                    HumanMove(ship.SN, detail_dr, detail_ur);
                    DebugText("战船" + to_string(ship.SN) + "探索(" +
                             to_string(target.first) + "," + to_string(target.second) + ")");
                }
                break;

            case SHIP_ATTACKING:
                // 战斗结束后返回探索状态
                if (ship.NowState == HUMAN_STATE_IDLE) {
                    ship_states[ship.SN] = SHIP_EXPLORING;
                }
                break;

            case SHIP_RETURNING:
                // 返回基地逻辑
                break;
        }

        // 实时检测敌方大陆
        detect_enemyland();
    }
}

void UsrAI::detect_enemyland() {
    if (enemy_land_discovered) return;


    for (auto &ship : army_ship) {
        int x = ship.BlockDR;
        int y = ship.BlockUR;

        for (int dx = -7; dx <= 7; dx++) {
            for (int dy = -7; dy <= 7; dy++) {
                int nx = x + dx;
                int ny = y + dy;
                if (nx < 0 || nx >= 128 || ny < 0 || ny >= 128) continue;


                if ((*info.theMap)[nx][ny].type == MAPPATTERN_GRASS &&
                        !explored_ocean[nx][ny] && enemy_near_block_water.size()) {
                    landing_poi = enemy_near_block_water.back();
                    enemy_land_discovered = true;
                    cout << "enemy_land poi is : " << landing_poi.first << ' ' << landing_poi.second << '\n';
                    DebugText("发现敌方大陆！登陆点: (" + to_string(nx) + "," + to_string(ny) + ")");
                    return;
                }
            }
        }
    }
}


//-----------------------------运输船模块------------------------------------

static bool update_our_grass = false;
static bool update_our_near_water_block = false;
static bool is_building_wood_boat = false;


vector<int> boarded_farmers; // 已登船村民的SN列表
int transport_ship_sn = -1;       // 运输船的SN
bool ship_at_shore = false;       // 运输船是否已靠岸
bool transporting = false;        // 是否正在运输过程中
bool arrived = false;             // 是否已到达敌方大陆
static const int FARMERS_TO_BOARD = 3; // 需要运送的村民数量
PII gathering_point;              // 我方大陆集合点坐标

PII our_attempt_poi;

void UsrAI::processData() {

    // 获得游戏状态
    info = getInfo();

    // cur_map存储当前地图
    UsrAI::BuildMap();

    // 更新被占用空间
    UsrAI::Init_SpaceMap();

    // 更新资源地图
    UsrAI::ResourceMap();

    // 初始化己方大陆
    if (!update_our_grass) {
        update_our_grass = true;
        for (int i = 0; i < 128; i ++) {
            for (int j = 0; j < 128; j ++) {
                if ((*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                    our_grassmap[i][j] = true;
                }
            }
        }
    }

    // 初始化敌方大陆
    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j <128; j ++) {
            if (!our_grassmap[i][j] && (*info.theMap)[i][j].type == MAPPATTERN_GRASS) {
                enemy_grassmap[i][j] = true;
            }
        }
    }

    // 初始化岸边方块
    if (!update_our_near_water_block) {
        for (int i = 0; i < 128; i ++) {
            for (int j = 0; j < 128; j ++) {
                if (our_grassmap[i][j]) {
                    if (cur_map[i + 1][j] == '#') {
                        our_near_water_block.push_back({i, j});
                        our_near_block_water.push_back({i + 1, j});
                    } else if (cur_map[i][j + 1] == '#') {
                        our_near_water_block.push_back({i, j});
                        our_near_block_water.push_back({i, j + 1});
                    } else if (cur_map[i - 1][j] == '#') {
                        our_near_water_block.push_back({i, j});
                        our_near_block_water.push_back({i - 1, j});
                    } else if (cur_map[i][j - 1] == '#') {
                        our_near_water_block.push_back({i, j});
                        our_near_block_water.push_back({i, j - 1});
                    }
                }
            }
            update_our_near_water_block = true;
        }
    }

    // 敌方岸边方块
    for (int i = 0; i < 128; i ++) {
        for (int j = 0; j < 128; j ++) {
            if (enemy_grassmap[i][j]) {
                if (cur_map[i + 1][j] == '#') {
                    enemy_near_water_block.push_back({i, j});
                    enemy_near_block_water.push_back({i + 1, j});
                } else if (cur_map[i][j + 1] == '#') {
                    enemy_near_water_block.push_back({i, j});
                    enemy_near_block_water.push_back({i, j + 1});
                } else if (cur_map[i - 1][j] == '#') {
                    enemy_near_water_block.push_back({i, j});
                    enemy_near_block_water.push_back({i - 1, j});
                } else if (cur_map[i][j - 1] == '#') {
                    enemy_near_water_block.push_back({i, j});
                    enemy_near_block_water.push_back({i, j - 1});
                }
            }
        }
    }
    // 初始化序列对资源类型的映射
    init_resources_buildings();

    // 查询村民状态
    find_farmers();

//    // 统计建筑数量
//    init_building_numbers();

    // 获取建筑数量
    cnt_home = cal_buildings(BUILDING_HOME);    // 房子
    cnt_farm = cal_buildings(BUILDING_FARM);    // 农田
    cnt_armycamp = cal_buildings(BUILDING_ARMYCAMP);    // 军营
    cnt_farmers = cal_farmers();    // 农民
    cnt_stock = cal_buildings(BUILDING_STOCK);
    cnt_dock = cal_buildings(BUILDING_DOCK);
    cnt_arrowtower = cal_buildings(BUILDING_ARROWTOWER);
    cnt_granary = cal_buildings(BUILDING_GRANARY);
    cnt_market = cal_buildings(BUILDING_MARKET);
    cnt_sailings = cal_ships(BUILDING_DOCK_CREATE_SAILING);
    cnt_wood_boats = cal_ships(BUILDING_DOCK_CREATE_WOOD_BOAT);

    // 统计军用单位
    cnt_ships = cal_army(AT_SHIP); // 战船
    cnt_bowman = cal_army(AT_BOWMAN); // 弓兵
    cnt_clubman = cal_army(AT_CLUBMAN); // 棍棒兵
    cnt_slinger = cal_army(AT_SLINGER); // 投石兵
    cnt_swordsman = cal_army(AT_SWORDSMAN); // 战斧兵
    cnt_scout = cal_army(AT_SCOUT); // 骑兵

    cnt_enemy_ship = cal_enemy(AT_SHIP); // 战船
    cnt_enemy_bowman = cal_enemy(AT_BOWMAN); // 弓兵
    cnt_enemy_clubman = cal_enemy(AT_CLUBMAN); // 棍棒兵
    cnt_enemy_slinger = cal_enemy(AT_SLINGER); // 投石兵
    cnt_enemy_swordsman = cal_enemy(AT_SWORDSMAN); // 战斧兵
    cnt_enemy_scout = cal_enemy(AT_SCOUT); // 骑兵


    //集结点为沿海平坦陆地
    if (our_attempt_poi.first == -1)
    {
        for (auto &y : our_near_water_block) {
            int xx = y.first, yy = y.second;
            tagBuilding dock;
            for (auto &e : info.buildings) {
                if (e.Type == BUILDING_DOCK) {
                    dock = e;
                    break;
                }
            }
            int x1 = dock.BlockDR, y1 = dock.BlockUR;
            if (abs(xx - x1) <= 7 || abs(yy - y1) <= 7) continue;
            if (abs(xx - x1) >= 15 || abs(yy - y1) >= 15) continue;
            our_attempt_poi = {xx, yy};
            break;
        }
    }

    if (info.GameFrame % 1000 == 0)
    {
        for (auto &e : info.farmers)
        {
            if (e.FarmerSort == 0 && e.NowState == HUMAN_STATE_WALKING)
            {
                HumanMove(e.SN, e.DR, e.UR);
            }
        }
    }

    // 原始时代
    if (info.civilizationStage == CIVILIZATION_STONEAGE) {
//         增加资源，作弊函数
//        static int cheat_times = 4;
//        while (cheat_times > 0) {
//            cheatRes();
//            cheat_times --;
//        }

        // 如果农民少于八个，则持续生产农民（判断条件已经在函数里写好了）
        if  (cnt_farmers < 8) {
            Building_produce(BUILDING_CENTER_CREATEFARMER);
        }

        // 在瞪羚聚集地附近建一个仓库，加快造渔船前的食物收集时间
        if (info.Wood >= 120 && cnt_stock == 1 && farmer_building_stock.empty()) {
            bool flag = false;
            for (auto &e : info.resources) {
                if (e.Type == RESOURCE_GAZELLE) {
                    flag = true;
                    int x = e.BlockDR, y = e.BlockUR;

                    auto t = bfs(x, y);

                    if (farmer_idle.size()) {
                        auto &m = farmer_idle.back();
                        farmer_idle.pop_back();

                        farmers_building(BUILDING_STOCK, m, t.first, t.second);
                        farmer_building_stock.push_back(m);

                    } else {
                        auto &m = farmer_cut_tree.back();
                        farmer_cut_tree.pop_back();

                        HumanMove(m.SN, m.DR, m.UR);

                        farmers_building(BUILDING_STOCK, m, t.first, t.second);
                        farmer_building_stock.push_back(m);
                    }
                }

                if (flag) break;
            }
        }
        // 寻找村民去打猎
        if (farmer_hunting.size() == 0) {
            if (farmer_idle.size()) {
                tagFarmer y;
                double dis = 1e8;
                for (auto &e : info.resources) {
                    if (e.Type == RESOURCE_GAZELLE) { // 寻找最近的瞪羚
                        for (auto &q : farmer_idle) {
                            double dis_t = cal_dis(e.DR, e.UR, q.DR, q.UR);

                            if (dis_t < dis) {
                                dis_t = dis;
                                y = q;
                            }
                        }
                    }
                }
                farmer_idle.pop_back();

                farmers_to_work(y, RESOURCE_GAZELLE);
                farmer_hunting.push_back(y);
            }
        }

        // 建四个房屋
        if (info.Human_MaxNum < 50 && farmer_idle.size() && info.Wood >= 200 && cnt_home < 4) {
            pair<int, int> ob_pos;

            auto pos_center = find_Center();
            auto &e = farmer_idle.back();
            farmer_idle.pop_back();

            auto pos_building = bfs(pos_center.first, pos_center.second);

            if (pos_building.first != 0) {
                farmers_building(BUILDING_HOME, e, pos_building.first, pos_building.second);
            }
        }

        if (info.Wood >= 150 && cnt_home >= 2 && farmer_idle.size()) {
            // 如果船坞数量小于2且正在造船坞的村民小于2，则挑选合适的地方建造船坞
            if (cnt_dock < 2 && farmer_building_dock.size() < 2) {

                for (auto &e : info.resources) {
                    int ob_x = 0, ob_y = 0;
                    if (e.Type == RESOURCE_FISH) {

                        cout << "find fish poi " << e.BlockDR << ' ' << e.BlockUR << endl;
                        double dis = 128*128*BLOCKSIDELENGTH;

                        for (int i = 0; i < 128; i ++) {
                            for (int j = 0; j < 128 ; j ++) {
                                if (find_water(i, j).first != -1) {
                                    cout << "find_water " << i << ' ' << j << endl;
                                    int now_x = find_water(i, j).first, now_y = find_water(i, j).second;

                                    cout << "target dock poi is " << now_x << ' ' << now_y << endl;
                                    if (dis > cal_dis(e.DR, e.UR, now_x*BLOCKSIDELENGTH, now_y*BLOCKSIDELENGTH)) {
                                        dis = cal_dis(e.DR, e.UR, now_x*BLOCKSIDELENGTH, now_y*BLOCKSIDELENGTH);
                                        ob_x = now_x, ob_y = now_y;
                                    }
                                }
                            }
                        }

                        auto &y = farmer_idle.back();
                        farmer_idle.pop_back();

                        cout << "Let farmer cutting tree build dock\n";
                        cout << "The huamn's SN is " << y.SN << endl;

                        cout << "The human's position is " << y.BlockDR << ' ' << y.BlockUR << endl;


                        cout << "The ob_dock_postion is " << ob_x << ob_y << endl;
                        farmers_building(BUILDING_DOCK, y, ob_x, ob_y);
                        farmer_building_dock.push_back(y);
                        break;
                    }
                }

            }
        }

        cout << "the number of sailings is: " << cnt_sailings << '\n';
        // 造渔船
        if (cnt_sailings < 4 && cnt_dock > 0 && info.Wood >= BUILDING_DOCK_CREATE_SAILING_WOOD) {
            Building_produce(BUILDING_DOCK_CREATE_SAILING);
        }

        // 让渔船打鱼
        find_fish();

        if (cnt_dock > 0 && cnt_stock > 0 && info.Meat >= 500) {
            for (auto &e : info.buildings) {
                if (e.Type == BUILDING_CENTER) {
                    BuildingAction(e.SN, BUILDING_CENTER_UPGRADE);
                }
            }
        }

        // 写在最后
        // 如果有闲置的村民，则安排砍树
        if (farmer_idle.size()) {
            while (farmer_idle.size()) {
                auto &e = farmer_idle.back();
                farmer_idle.pop_back();

                farmers_to_work(e, RESOURCE_TREE);
                farmer_cut_tree.push_back(e);
            }
        }
    } else if (info.civilizationStage == CIVILIZATION_TOOLAGE) {
        // 工具时代
            // 让渔船打鱼
            find_fish();

            // 生产村民数量到10个
            cout << "farmers number is : " << cnt_farmers << '\n';
            if (cnt_farmers < 10) {
                Building_produce(BUILDING_CENTER_CREATEFARMER);
            }

            cout <<"idle farmers's number is : " << farmer_idle.size() << '\n';

            // 建造谷仓
            cout << "granary's number is : " << cnt_granary << '\n';
            if (cnt_granary == 0 && info.Wood >= 120 && farmer_building_granary.size() == 0) {
                auto pos_home = find_Home();
                if (pos_home.first != -1) {
                    if (farmer_idle.size()) {

                        auto pos_building = bfs(pos_home.first, pos_home.second);

                        if (pos_building.first != 0) {
                            tagFarmer &e = farmer_idle.back();
                            farmer_idle.pop_back();
                            farmers_building(BUILDING_GRANARY, e, pos_building.first, pos_building.second);
                        }
                    }
                }
            }

            // 建造市场
            cout << "market number is : " << cnt_market << '\n';
            if (cnt_granary == 1 && cnt_market == 0 && info.Wood >= 150 && farmer_building_market.size() == 0) {
                auto pos_home = find_Home();
                if (pos_home.first != -1) {
                    if (farmer_idle.size()) {

                        auto pos_building = bfs(pos_home.first, pos_home.second);

                        if (pos_building.first != 0) {
                            tagFarmer &e = farmer_idle.back();
                            farmer_idle.pop_back();
                            farmers_building(BUILDING_MARKET, e, pos_building.first, pos_building.second);
                        }
                    }
                }
            }

            // 建造农场
            cout << "farm number is : " << cnt_farm << '\n';
            if (cnt_market == 1 && cnt_farm < 1 && info.Wood >= 75 && farmer_building_farm.size() == 0) {
                auto pos_home = find_Home();
                if (pos_home.first != -1) {
                    if (farmer_idle.size()) {

                        auto pos_building = bfs(pos_home.first, pos_home.second);

                        if (pos_building.first != 0) {
                            tagFarmer &e = farmer_idle.back();
                            farmer_idle.pop_back();
                            farmers_building(BUILDING_FARM, e, pos_building.first, pos_building.second);
                        }
                    }
                }
            }

            // 建造房屋
            cout << "max_human_num : " <<info.Human_MaxNum << '\n';

            cout << "home number is : " << cnt_home << '\n';
            if (info.Human_MaxNum < 50 && info.Wood >= 100 && cnt_home < 9) {
                auto pos_center = find_Center();
                if (pos_center.first != 0) {
                    if (farmer_idle.size()) {

                        auto pos_building = bfs(pos_center.first, pos_center.second);

                        if (pos_building.first != 0) {
                            tagFarmer &e = farmer_idle.back();
                            farmer_idle.pop_back();
                            farmers_building(BUILDING_HOME, e, pos_building.first, pos_building.second);
                        }
                    }
                }
            }

            // 建造战船
            if (cnt_farm) {
                if (cnt_ships < 12 && info.Wood >= BUILDING_DOCK_CREATE_SHIP_WOOD) {
                    Building_produce(BUILDING_DOCK_CREATE_SHIP);
                }
            }

            // 战船出海
            cout << "ship number : " << cnt_ships << '\n';
            cout << "enemy_ship : " << cnt_enemy_ship << '\n';
            // 集体探索逻辑
            static int frames = 0;
            static bool ship_start = false;
            if (cnt_ships >= 11 && !ship_start) {
                ship_start = true;
                auto pos = find_Center();
                for (auto &e : info.armies)
                {
                    if (e.Sort == AT_SHIP)
                    {
                        if (e.NowState == HUMAN_STATE_IDLE && !enemy_land_discovered)
                        {
                            HumanMove(e.SN, (128 - pos.first) * BLOCKSIDELENGTH, (128 - pos.second) * BLOCKSIDELENGTH);
                        }
                        else if (enemy_land_discovered)
                        {
                            if (frames == 0) frames = info.GameFrame;
                            if (info.GameFrame <= frames + 1500) order_ship_explore();
                        }
                    }
                }
                attack(AT_SHIP);
            }
            else if (ship_start)
            {
                auto pos = find_Center();
                for (auto &e : info.armies)
                {
                    if (e.Sort == AT_SHIP)
                    {
                        if (e.NowState == HUMAN_STATE_IDLE && !enemy_land_discovered)
                        {
                            HumanMove(e.SN, (128 - pos.first) * BLOCKSIDELENGTH, (128 - pos.second) * BLOCKSIDELENGTH);
                        }
                        else if (enemy_land_discovered)
                        {
                            if (frames == 0) frames = info.GameFrame;
                            if (info.GameFrame <= frames + 1500) order_ship_explore();
                        }
                    }
                }
                attack(AT_SHIP);
            }
            attack(AT_SHIP);

            static bool adjust_wood_boat = false;
            if (!adjust_wood_boat && enemy_land_discovered)
            {
                for (auto e : info.farmers)
                {
                    if (e.FarmerSort == 1)
                    {
                        HumanMove(e.SN, e.DR, e.UR);
                    }
                }
                adjust_wood_boat = true;
            }

            // 检测敌方大陆
            if (!enemy_land_discovered) {
                for (auto &ship : army_ship) {
                    int x = ship.BlockDR;
                    int y = ship.BlockUR;

                    // 检查周围16x16区域
                    for (int dx = -8; dx <= 8; dx++) {
                        for (int dy = -8; dy <= 8; dy++) {
                            int nx = x + dx;
                            int ny = y + dy;
                            if (nx < 0 || nx >= 128 || ny < 0 || ny >= 128) continue;

                            if ((*info.theMap)[nx][ny].type == MAPPATTERN_GRASS &&
                                !our_grassmap[nx][ny]) { // 非我方大陆
                                enemy_land_discovered = true;
                                enemy_base_center = {nx, ny};
                                landing_poi = {nx, ny};
                                explore_targets.clear(); // 停止探索
                                DebugText("发现敌方大陆！位置: (" + to_string(nx) + "," + to_string(ny) + ")");
                                break;
                            }
                        }
                    }
                    if (enemy_land_discovered) break;
                }
            }

            // 建造运输船
            static bool is_building_boat = false;
            if (cnt_wood_boats == 0 &&  ! is_building_boat &&// 当前没有运输船
                    info.Wood >= BUILDING_DOCK_CREATE_WOOD_BOAT_WOOD) { // 不在建造中
                // 触发建造命令
                Building_produce(BUILDING_DOCK_CREATE_WOOD_BOAT);
                is_building_boat = true;// 标记为正在建造
            }

            if (cnt_farmers < 13 && info.Meat >= BUILDING_CENTER_CREATEFARMER_FOOD) {
                Building_produce(BUILDING_CENTER_CREATEFARMER);
            }


            // 运输阶段：运输船靠岸 -> 村民上船 -> 运输到敌方大陆
            if (enemy_land_discovered && cnt_wood_boats > 0) {
                // 步骤1：获取运输船
                if (transport_ship_sn == -1) {
                    for (auto &f : info.farmers) {
                        if (f.FarmerSort == 1) { // 1表示运输船
                            transport_ship_sn = f.SN;
                            DebugText("找到运输船 SN: " + to_string(transport_ship_sn));

                            // 设置集合点（市镇中心附近靠水位置）
                            auto center = find_Center();
                            gathering_point = find_near_water(center.first, center.second);
                            DebugText("设置集合点: (" + to_string(gathering_point.first) +
                                     "," + to_string(gathering_point.second) + ")");
                            break;
                        }
                    }
                }

                // 步骤2：运输船靠岸
                if (transport_ship_sn != -1 && !ship_at_shore) {
                    tagFarmer* transport_ship = nullptr;
                    for (auto &f : info.farmers) {
                        if (f.SN == transport_ship_sn) {
                            transport_ship = &f;
                            break;
                        }
                    }

                    if (transport_ship) {
                        // 计算运输船当前位置与集合点的距离
                        double dist_to_shore = cal_dis(
                            transport_ship->DR, transport_ship->UR,
                            gathering_point.first * BLOCKSIDELENGTH,
                            gathering_point.second * BLOCKSIDELENGTH
                        );

                        // 如果运输船空闲且未靠岸，发送移动指令
                        if (transport_ship->NowState == HUMAN_STATE_IDLE && dist_to_shore > 100.0) {
                            double target_dr = gathering_point.first * BLOCKSIDELENGTH;
                            double target_ur = gathering_point.second * BLOCKSIDELENGTH;
                            HumanMove(transport_ship_sn, target_dr, target_ur);
                            DebugText("运输船前往集合点: (" +
                                     to_string(gathering_point.first) + "," +
                                     to_string(gathering_point.second) + ")");
                        }
                        // 检查是否已靠岸
                        else if (dist_to_shore <= 150.0) {
                            ship_at_shore = true;
                            DebugText("运输船已靠岸!");
                        }
                    }
                }

                // 步骤3：村民登船（运输船靠岸后才能登船）
                if (ship_at_shore && boarded_farmers.size() < FARMERS_TO_BOARD) {
                    for (auto &farmer : info.farmers) {
                        // 只让陆地村民登船，且不在运输过程中
                        if (farmer.FarmerSort == 0 && farmer.NowState == HUMAN_STATE_IDLE) {
                            // 检查是否已登船
                            if (find(boarded_farmers.begin(), boarded_farmers.end(), farmer.SN) == boarded_farmers.end()) {
                                int ret = HumanAction(farmer.SN, transport_ship_sn);
                                if (ret > 0) {
                                    boarded_farmers.push_back(farmer.SN);
                                    DebugText("村民 " + to_string(farmer.SN) + " 登船");
                                    transporting = true;
                                }
                            }
                        }

                        // 达到所需村民数量后停止
                        if (boarded_farmers.size() >= FARMERS_TO_BOARD) break;
                    }
                }

                // 步骤4：运输船航行（村民登船完成后）
                if (transporting && !arrived) {
                    // 找到运输船对象
                    tagFarmer* transport_ship = nullptr;
                    for (auto &f : info.farmers) {
                        if (f.SN == transport_ship_sn) {
                            transport_ship = &f;
                            break;
                        }
                    }

                    if (transport_ship) {
                        // 检查是否已到达敌方大陆
                        if (enemy_grassmap[transport_ship->BlockDR][transport_ship->BlockUR]) {
                            arrived = true;
                            DebugText("运输船已到达敌方大陆!");
                        }
                        // 如果未移动或空闲，发送移动指令
                        else if (transport_ship->NowState == HUMAN_STATE_IDLE) {
                            // 计算登陆点细节坐标
                            double target_dr = landing_poi.first * BLOCKSIDELENGTH;
                            double target_ur = landing_poi.second * BLOCKSIDELENGTH;

                            HumanMove(transport_ship_sn, target_dr, target_ur);
                            DebugText("运输船前往登陆点: (" +
                                     to_string(landing_poi.first) + "," +
                                     to_string(landing_poi.second) + ")");
                        }
                    }
                }

                // 步骤5：村民下船（自动处理）
                if (arrived) {
                    // 检查村民是否已下船（重新出现在农民列表中）
                    for (auto it = boarded_farmers.begin(); it != boarded_farmers.end();) {
                        bool found = false;
                        for (auto &farmer : info.farmers) {
                            if (farmer.SN == *it) {
                                // 村民已在敌方大陆
                                if (enemy_grassmap[farmer.BlockDR][farmer.BlockUR]) {
                                    DebugText("村民 " + to_string(*it) + " 已登陆敌方大陆");

                                    // 在这里可以添加村民在敌方大陆的行动指令
                                    // 例如：建造兵营、采集资源等

                                    it = boarded_farmers.erase(it);
                                    found = true;
                                    break;
                                }
                            }
                        }
                        if (!found) ++it;
                    }

                    // 所有村民都已下船，重置状态
                    if (boarded_farmers.empty()) {
                        transporting = false;
                        arrived = false;
                        transport_ship_sn = -1;
                        ship_at_shore = false;
                    }
                }
            }

            // 寻找村民去打猎
            if (farmer_hunting.size() == 0) {
                if (farmer_idle.size()) {
                    tagFarmer y;
                    double dis = 1e8;
                    for (auto &e : info.resources) {
                        if (e.Type == RESOURCE_GAZELLE) { // 寻找最近的瞪羚
                            for (auto &q : farmer_idle) {
                                double dis_t = cal_dis(e.DR, e.UR, q.DR, q.UR);

                                if (dis_t < dis) {
                                    dis_t = dis;
                                    y = q;
                                }
                            }
                        }
                    }
                    farmer_idle.pop_back();

                    farmers_to_work(y, RESOURCE_GAZELLE);
                    farmer_hunting.push_back(y);
                }
            }

            // 派遣一名村民挖石头
//            if (farmer_pick_stone.size() < 1 && farmer_idle.size()) {
//                auto &e =farmer_idle.back();
//                farmer_idle.pop_back();
//                cout << "pick stone SN" << e.SN << '\n';
//                farmers_to_work(e, RESOURCE_STONE);
//                farmer_pick_stone.push_back(e);
//            }

            if (enemy_land_discovered) cout <<"find enemy_land\n" << landing_poi.first << ' ' <<landing_poi.second << '\n';

            // 如果有闲置的村民，则安排砍树
            if (farmer_idle.size()) {
                while (farmer_idle.size()) {
                    auto &e = farmer_idle.back();
                    farmer_idle.pop_back();

                    farmers_to_work(e, RESOURCE_TREE);
                    farmer_cut_tree.push_back(e);
                }
            }

        }

    return ;
}
